﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using RBS.Common;
using RBS.Common.DEncrypt;
using RBS.Common.JsonEntity;
using RBS.Core.BLL;
using RBS.Core.Model.Hotel;

namespace RBS.Web.Hotel.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        public ActionResult Index()
        {
            var msg = Request["msg"];

            if (msg != null)
            {
                ViewBag.msg = msg;
            } 
            return View();
        }  
        //登录
        [HttpPost]
        public ActionResult SignOn(FormCollection collection)
        {
            var bll = new RBS.Core.BLL.Hotel.H_Hotel_Users(); 
            var roleType = collection["roleType"];
            var model =   bll.UserLogin(collection["H_UID"], DESEncrypt.Encrypt(collection["Password"]));
            if (model != null)
            { 
               /* if (!model.RoleIds.Contains(roleType))
                {
                    return RedirectToAction("Index", new { msg = "此帐号没有当前角色信息" });
                }*/
                FormsAuthentication.SetAuthCookie(model.H_UID, false);
               // model.RoleIds = roleType; 

                Session[RBSKeys.SESSION_HOTEL_INFO] = model;
                Session.Timeout = 45; 
                //写入Cookies
                Utils.WriteCookie("DTRememberName", model.H_UserName, 14400);
                Utils.WriteCookie("AdminName", "DTcms", model.H_UID);
                Utils.WriteCookie("AdminPwd", "DTcms", model.Password);
                if (!User.Identity.IsAuthenticated)
                {
                    FormsAuthentication.SignOut();
                }
                FormsAuthentication.SetAuthCookie(model.Id.ToString(), false);  
                return RedirectToAction("Index", "Home");
            }
            else
            {
                return RedirectToAction("Index",new{msg="用户名或密码错误"});
            }  
        }
        //注销
        public ActionResult SignOut()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("Index", "Login"); 
        }

        #region 注册酒店
        public ActionResult Register()
        {

         // ViewBag.Location=Common.Api.Maps.Baidu.GetLocation();
            return View();
        }

        [HttpPost]
        public ActionResult Register(FormCollection collection)
        {
            try
            { 
                var hotels = new H_Hotels
                {
                    H_Name = collection["Hotels.H_Name"],
                    Mobile = collection["HotelUsers.H_UID"],
                    Telphone = collection["Hotels.Telphone"],
                    Address = collection["Hotels.Address"],
                    Location = collection["Hotels.Location"],
                    License = collection["Hotels.License"],
                    Province = collection["Province"],
                    City = collection["City"],
                    Region = collection["Region"],
                    IsRecommend =0 ,
                    Cuisine = "其他菜"  
                }; 
                var hotelbll = new RBS.Core.BLL.Hotel.H_Hotels();
                var hotelid= hotelbll.Add(hotels); 
                var user = new H_Hotel_Users
                {
                    H_UID = collection["HotelUsers.H_UID"],
                    H_UserName = collection["HotelUsers.H_UserName"],
                    Password = DESEncrypt.Encrypt(collection["Password"]),
                    HotelId = hotelid,
                    RoleIds = "1",
                    regTime = DateTime.Now
                }; 
                // TODO: Add insert logic here 
                var userbll = new RBS.Core.BLL.Hotel.H_Hotel_Users();
               var userId=  userbll.Add(user);

               if (hotelid>0 && userId>0)
               {
                   FormsAuthentication.SetAuthCookie(user.H_UID, false);
                   Session[RBSKeys.SESSION_HOTEL_INFO] = user;
                   Session["Hotels"] = hotels;
               } 
               #region 往高德地图添加标注   
                var hotelMapBll = new RBS.Core.BLL.H_HotelMap();
                var mapInfo = hotelMapBll.AMapAdd("", hotels.H_Name, hotels.Address, hotels.Location, hotelid);
                var map = new RBS.Core.Model.H_HotelMap
                    {
                        HotelId = hotels.H_id,
                        MapId = mapInfo._id,
                        lng = hotels.Location.Split(',')[0],
                        lat = hotels.Location.Split(',')[1]
                    };
                hotelMapBll.Save(map);
               #endregion

                //{"info":"OK","status":1,"_id":"3"}
               var stcript = "$.dialog.alert('注册成功！');window.location.href='" + @Url.Action("Index") + "'";
               return Content(stcript, "application/x-javascript"); 
            }
            catch
            {
                return View("Index");
            }
        }

        public ActionResult Registeramap()
        {

            // ViewBag.Location=Common.Api.Maps.Baidu.GetLocation();
            return View();
        }
        
        [HttpPost]
        public ActionResult Registeramap(FormCollection collection)
        {
            try
            { 
                var hotels = new H_Hotels
                {
                    H_Name = collection["Hotels.H_Name"],
                    Mobile = collection["HotelUsers.H_UID"],
                    Telphone = collection["Hotels.Telphone"],
                    Address = collection["Hotels.Address"],
                    Location = collection["Hotels.Location"],
                    License = collection["Hotels.License"],
                    Province = collection["Province"],
                    City = collection["City"],
                    Region = collection["Region"],
                    IsRecommend =0 ,
                    Cuisine = ""  
                }; 
                var hotelbll = new RBS.Core.BLL.Hotel.H_Hotels();
                var hotelid= hotelbll.Add(hotels); 
                var user = new H_Hotel_Users
                {
                    H_UID = collection["HotelUsers.H_UID"],
                    H_UserName = collection["HotelUsers.H_UserName"],
                    Password = DESEncrypt.Encrypt(collection["Password"]),
                    HotelId = hotelid,
                    RoleIds = "1",
                    regTime = DateTime.Now
                }; 
                // TODO: Add insert logic here 
                var userbll = new RBS.Core.BLL.Hotel.H_Hotel_Users();
               var userId=  userbll.Add(user);

               if (hotelid>0 && userId>0)
               {
                   FormsAuthentication.SetAuthCookie(user.H_UID, false);
                   Session[RBSKeys.SESSION_HOTEL_INFO] = user;
                   Session["Hotels"] = hotels;
               }

               #region 往高德地图添加标注 
              
              
                var hotelMapBll = new RBS.Core.BLL.H_HotelMap();
                var mapInfo = hotelMapBll.AMapAdd("", hotels.H_Name, hotels.Address, hotels.Location, hotels.H_id);
                var map = new RBS.Core.Model.H_HotelMap
                    {
                        HotelId = hotels.H_id,
                        MapId = mapInfo._id,
                        lng = hotels.Location.Split(',')[0],
                        lat = hotels.Location.Split(',')[1]
                    };
                hotelMapBll.Save(map);
               #endregion

                //{"info":"OK","status":1,"_id":"3"}
               var stcript = "$.dialog.alert('注册成功！');window.location.href='" + @Url.Action("Index") + "'";
               return Content(stcript, "application/x-javascript"); 
            }
            catch
            {
                return View("Index");
            }
        }
        #endregion
        #region 密码找回
        public ActionResult Resetpassword()
        {
            ViewBag.msg=Request["msg"];
           
            return View();
        } 
        [HttpPost]
        public ActionResult Resetpassword(FormCollection collection)
        {
            try
            {  
                var H_UID = collection["H_UID"];
                var bll = new RBS.Core.BLL.Hotel.H_Hotel_Users();
               var model= bll.GetModelByCache(H_UID);
                if (model == null)
                {
                    return RedirectToAction("resetpassword", new { msg = "手机号码没有注册！" });
                     // return Content("手机号码没有注册");
                }
                var newpwd = RBS.Common.Utils.Number(6);
                model.Password = DESEncrypt.Encrypt(newpwd);
                bll.Update(model); 
                var content = "您的新密码为：'" + newpwd + "'，请登录网站及时修改！";
                string msg="";
                new RBS.Core.BLL.SmsMessage().Send(H_UID, content, 1,out msg); 
                return RedirectToAction("Index", new { msg = "发送成功！"});
            }
            catch
            {
                return View("Index");
            }
        }
        #endregion
         
        #region 图片上传
        /// <summary>
        /// 营业执照上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadImg()
        {  
            string outpath = "UploadImages" + "\\" + "License\\";
            string physicalPath = HttpContext.Server.MapPath("~/") + outpath;
            if (!Directory.Exists(physicalPath))
            {
                Directory.CreateDirectory(physicalPath);
            }
            try
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        var postedFileBase = Request.Files[i];
                        if (postedFileBase != null)
                        {
                            string filename = DateTime.Now.ToString("yyyyMMddhhmmss")+System.IO.Path.GetFileName(postedFileBase.FileName);
                            httpPostedFileBase.SaveAs(physicalPath + filename);
                            outpath += filename; 
                        } 
                    }
                }
            }
            catch (Exception ex)
            {
                outpath = ""; 
            } 
            return Content("../"+outpath);
        }

       #endregion

    }

   
}
